#include "../third_party/httplib.h"
#include "../third_party/json.hpp"
#include "hot_manager.h"
#include "breakpoint_manager.h"
#include <fstream>
using json = nlohmann::json;
using namespace httplib;

HotFileManager hot_mgr;
BreakpointManager bp_mgr;

int main() {
    Server svr;
    // 上传接口，支持断点续传
    svr.Post("/upload", [](const Request& req, Response& res) {
        std::string filename = req.get_param_value("filename");
        size_t offset = std::stoull(req.get_param_value("offset"));
        std::ofstream ofs("data/" + filename, std::ios::binary | std::ios::app);
        ofs.seekp(offset);
        ofs.write(req.body.c_str(), req.body.size());
        ofs.close();
        bp_mgr.save_progress(filename, offset + req.body.size());
        hot_mgr.access(filename);
        res.set_content("{\"status\":\"ok\"}", "application/json");
    });
    // 查询断点
    svr.Get("/progress", [](const Request& req, Response& res) {
        std::string filename = req.get_param_value("filename");
        size_t offset = bp_mgr.get_progress(filename);
        json j = { {"offset", offset} };
        res.set_content(j.dump(), "application/json");
    });
    // 热点文件查询
    svr.Get("/hot", [](const Request& req, Response& res) {
        auto files = hot_mgr.get_hot_files();
        json j = files;
        res.set_content(j.dump(), "application/json");
    });
    // 下载接口
    svr.Get("/download", [](const Request& req, Response& res) {
        std::string filename = req.get_param_value("filename");
        std::ifstream ifs("data/" + filename, std::ios::binary);
        if (!ifs) {
            res.status = 404;
            return;
        }
        std::string content((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
        res.set_content(content, "application/octet-stream");
        hot_mgr.access(filename);
    });
    system("mkdir data");
    svr.listen("0.0.0.0", 8080);
    return 0;
} 